package main.com.cyz.Stack;

import main.com.cyz.Stack.Bean.MyStack;
import org.junit.platform.engine.support.hierarchical.Node;

import java.util.Iterator;

/**
 * @author fox
 * @version 1.0
 * @description 手写数组栈
 * @date 2024/5/19 21:47
 */
public class MyArrayListStack<E> implements MyStack<E>,Iterable<E> {

    private E[] array;
    private int top;

    public MyArrayListStack(int capacity) {
        this.array = (E[]) new Object[capacity];
    }

    @Override
    public Boolean push(E value) {
        if (isFull()){
            return false;
        }
        array[top++] = value;
        return true;
    }

    @Override
    public E pop() {
        if (isEmpty()){
            return null;
        }
        E value = array[--top];
        return value;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return array[top - 1];
    }

    @Override
    public Boolean isEmpty() {
        return top == 0;
    }

    @Override
    public Boolean isFull() {
        return top == array.length;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            int point = top;

            @Override
            public boolean hasNext() {
                return point != 0;
            }

            @Override
            public E next() {
                return array[--point];
            }
        };
    }
}
